const app = getApp();

Page({
  data: {
    tabs: ['全部', '进行中', '退款/售后', '已完成'],
    currentTab: 0,
    orderStatus: 'all',
    orderStatusList: ['all', 'inProgress', 'refunded', 'done'],
    currentList: [], // 当前显示的数据
    page: 1, // 当前页码
    userId: '', // 用户ID
  },

  onLoad: function () {},

  onShow: function () {
    this.ensureUserId().then(() => {
      this.getOrderList(); // 每次页面显示时重新获取订单列表
    });
  },

  /** 确保 userId 存在 */
  ensureUserId: function () {
    return new Promise((resolve, reject) => {
      let userId = wx.getStorageSync('openId');
      if (userId) {
        this.setData({ userId });
        resolve(userId);
      } else {
        wx.cloud.callFunction({
          name: 'xiaoBangCommonFunction',
          data: {
            getUserInfoRequest: {}
          },
          success: (res) => {
            console.log('获取 userId 成功: ', res);
            userId = res.result.data.userId;
            wx.setStorageSync('openId', userId); // 缓存 userId
            this.setData({ userId });
            resolve(userId);
          },
          fail: (err) => {
            console.error('获取 userId 失败: ', err);
            wx.showToast({
              title: '无法获取用户信息',
              icon: 'none',
            });
            reject(err);
          },
        });
      }
    });
  },

  /** 获取订单列表 */
  getOrderList: function () {
    const { userId, page, currentList, orderStatus } = this.data;
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getOrderListRequest: {
            userId,
            orderStatus,
            page,
          }
        },
        success: (res) => {
          console.log('>>>订单列表: ', res.result.data);
          const newList =
            page === 1
              ? res.result.data.orders
              : [...currentList, ...res.result.data.orders];

          this.setData({
            currentList: newList,
          });
          if(this.data.currentList.length === 0) {
            wx.showToast({
              title: '暂无订单信息',
            })
          }
          wx.hideLoading();
          resolve(newList);
        },
        fail: (err) => {
          console.error('[云函数] [getOrderList] 调用失败', err);
          wx.hideLoading();
          reject(err);
        },
      });
    });
  },

  /** 切换 Tab */
  switchTab: function (e) {
    const index = e.currentTarget.dataset.index;
    const status = this.data.orderStatusList[index];
    console.log('切换到 Tab: ', index, status);

    this.setData({
      currentTab: index,
      orderStatus: status, // 修复直接用变量 status
      page: 1, // 切换 Tab 时重置分页
    });

    this.getOrderList();
  },

  /** 上拉加载更多 */
  onReachBottom: function () {
    console.log('触发上拉加载更多');
    const newPage = this.data.page + 1;
    this.setData({ page: newPage });
    this.getOrderList();
  },

  /** 下拉刷新 */
  onPullDownRefresh: function () {
    console.log('触发下拉刷新');
    this.setData({ page: 1 }); // 重置到第一页
    this.getOrderList().finally(() => {
      wx.stopPullDownRefresh(); // 停止下拉刷新动画
    });
  },

  /** 投诉 */
  complaint(e) {
    const { orderid } = e.currentTarget.dataset;
    console.log('投诉订单 ID: ', orderid);
    wx.navigateTo({
      url: `/pages/addComplaint/index?orderId=${orderid}`,
    });
  },

  /** 查看投诉进度 */
  viewComplaint(e) {
    const { orderid } = e.currentTarget.dataset;
    console.log('查看投诉进度订单 ID: ', orderid);
    wx.navigateTo({
      url: `/pages/complaintProgress/index?orderId=${orderid}`,
    });
  },

  /** 取消订单 */
  cancelOrder(e) {
    const { orderid } = e.currentTarget.dataset;

    wx.showModal({
      title: '取消订单',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 显示 loading
          wx.showLoading({
            title: '处理中...',
            mask: true  // 防止触摸穿透
          });
          wx.cloud.callFunction({
            name: 'xiaoBangCommonFunction',
            data: { 
              cancelOrderRequest: { 
                orderId: orderid 
              } 
            },
            success: (res) => {
              // 隐藏 loading
              wx.hideLoading();
              if (res.result.code === 200) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success',
                });

                const updatedList = this.data.currentList.filter(
                  (item) => item.orderId !== orderid
                );
                this.setData({ currentList: updatedList });
              } else {
                wx.showToast({
                  title: res.result.message || '取消失败',
                  icon: 'none',
                });
              }
            },
            fail: (err) => {
              wx.hideLoading();
              console.error('取消订单失败:', err);
              wx.showToast({
                title: '网络错误，取消订单失败',
                icon: 'none',
              });
            },
          });
        } else if (res.cancel) {
          wx.showToast({
            title: '已取消操作',
            icon: 'none',
          });
        }
      },
    });
  },

  /** 申请退款 */
  applyRefund(e) {
    const orderId = e.currentTarget.dataset.orderid;
    const btnIndex = e.currentTarget.dataset.btnindex;
    
    // 显示申请退款对话框，退款原因为必填
    wx.showModal({
      title: '骑手已接单，我们将通知骑手并退款',
      content: '',
      editable: true,
      placeholderText: '请输入退款原因（必填）...',
      success: (res) => {
        if (res.confirm) {
          const refundReason = res.content;
          
          // 验证退款原因是否为空
          if (!refundReason || refundReason.trim() === '') {
            wx.showToast({
              title: '退款原因不能为空',
              icon: 'none'
            });
            return;
          }
          
          this.callApplyRefundAPI(orderId, refundReason.trim());
        }
      }
    });
  },

  /** 调用申请退款API */
  async callApplyRefundAPI(orderId, refundReason) {
    try {
      wx.showLoading({ title: '申请中...' });
      
      // 第一步：调用申请退款接口
      const refundRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          updateOrderStatusRequest: {
            orderId: orderId,
            orderStatus: '退款中',
            refundReason: refundReason,
            refundApplyTime: new Date()
          }
        }
      });
      
      if (refundRes.result.code === 200) {
        // 第二步：申请退款成功后，获取最新的订单信息
        await this.refreshOrderById(orderId);
        
        wx.showToast({
          title: '我们将尽快处理',
          icon: 'success'
        });
      } else {
        wx.hideLoading();
        wx.showToast({
          title: refundRes.result.message || '申请失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('申请退款失败:', error);
      wx.showToast({
        title: '申请失败，请稍后重试',
        icon: 'none'
      });
    }
  },

  /** 根据订单ID获取最新订单信息并更新列表 */
  async refreshOrderById(orderId) {
    try {
      console.log('开始获取订单最新信息:', orderId);
      
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getOrderListRequest: {
            orderId: orderId, // 传入订单ID
            userId: this.data.userId // 传入用户ID确保权限
          }
        }
      });
      
      if (res.result.code === 200 && res.result.data.orders && res.result.data.orders.length > 0) {
        const updatedOrder = res.result.data.orders[0];
        console.log('获取到最新订单信息:', updatedOrder);
        
        // 更新订单列表中的对应订单
        this.updateOrderInList(updatedOrder);
        
        wx.hideLoading();
      } else {
        wx.hideLoading();
        console.error('获取订单信息失败:', res.result.message);
        // 如果获取失败，回退到刷新整个列表
        this.getOrderList();
      }
    } catch (error) {
      wx.hideLoading();
      console.error('获取订单信息异常:', error);
      // 如果获取失败，回退到刷新整个列表
      this.getOrderList();
    }
  },

  /** 更新订单列表中的指定订单 */
  updateOrderInList(updatedOrder) {
    const updatedList = this.data.currentList.map(item => {
      if (item.orderId === updatedOrder.orderId) {
        console.log('更新订单:', item.orderId, '新状态:', updatedOrder.orderStatus);
        return {
          ...item,
          ...updatedOrder  // 用最新的订单信息完全替换
        };
      }
      return item;
    });
    
    this.setData({ 
      currentList: updatedList 
    });
    
    console.log('订单列表已更新');
  },

  /** 跳转到订单详情 */
  goToOrderDetail(e) {
    const orderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: `/pages/orderDetail/index?orderId=${orderId}`,
    });
    console.log('跳转到订单详情: ', orderId);
  },
});